package cn.cht.mvcframework.servlet;

import cn.cht.mvcframework.annotations.*;
import cn.cht.mvcframework.demo.pojo.Handler;
import org.apache.commons.lang3.StringUtils;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MyDispatcherServlet extends HttpServlet {


    private Properties properties = new Properties();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));
        //初始化 bean对象 （实现ioc容器，基于注解）

        doInstance();

        //实现依赖注入
        doAutowired();
        //构造一个handlerMapping 处理器映射器 将配置好的url和method建立映射关系
        initHandlerMapping();
        System.out.println("MyDispatcherServlet 初始化完成~!");
        //等待请求进入,处理请求

    }

    //handlerMapping
//    private Map<String,Method> handlerMapping =new HashMap<>(); //存储url和method的映射关系
    private List<Handler>  handlerMapping=new ArrayList<>();
    //构造一个HandlerMapping 处理器映射器
    private void initHandlerMapping() {

        if (ioc.isEmpty()){return;}

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取ioc中当前遍历对象的class类型
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(MyController.class)){
                continue;
            }
            String baseUrl="";
            if (aClass.isAnnotationPresent(MyRequestMapping.class)){
                MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);
                baseUrl = annotation.value();//demo
            }
            //解析类上的 @MySecurity
            final Set<String> classUserNameSet;
            if (aClass.isAnnotationPresent(MySecurity.class)) {
                MySecurity mySecurity = aClass.getAnnotation(MySecurity.class);
                String[] value = mySecurity.value();
                classUserNameSet = Arrays.stream(value).collect(Collectors.toSet());

            } else {
                classUserNameSet = new HashSet<>();
            }

            //获取方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(MyRequestMapping.class)) {
                    //方法没有标识MyRequestMapping 
                    continue;
                }

                MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                String mehtodUrl = annotation.value(); //query
                String url=baseUrl+mehtodUrl; //url
                Set<String> usernames =new HashSet<>();
                //获取 MySecurity 注解
                if (method.isAnnotationPresent(MySecurity.class)) {
                    MySecurity mySecurity = method.getAnnotation(MySecurity.class);
                    String[] value = mySecurity.value();
                    usernames.addAll(Arrays.stream(value).collect(Collectors.toSet()));
                    usernames.addAll(classUserNameSet);
                    System.out.println("usernames:"+usernames);
                }else {
                    usernames.addAll(classUserNameSet);
                }


                //封装handler
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url),usernames);
                //计算参数位置 信息
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter=parameters[i];
                    if (parameter.getType() == HttpServletResponse.class ||parameter.getType() == HttpServletRequest.class){
                        //如果是request 和sesponse对象,那么参数名称写HttpServletResponse  HttpServletRequest
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }
                //建立url 和method 之间的映射关系  map缓存
                handlerMapping.add(handler);
            }
        }
    }

    //实现依赖注入
    private void doAutowired() {
        if (ioc.isEmpty()){
            return;
        }
        //有对象再进行依赖注入
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取 字段类型
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }
                //有注解
                MyAutowired annotation = field.getAnnotation(MyAutowired.class);
                String beanName = annotation.value(); //需要注入bean 的id

                if ("".equals(beanName.trim())){
                    //没有配置bean 的id ,那就需要根据当前字段类型注入
                    beanName=field.getType().getName();
                }
                //开启赋值
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //ioc
    private Map<String, Object> ioc = new HashMap<>();

    //IOC容器
    private void doInstance() {
        //基于classNames 缓存类的全限定类名,利用反射技术,完成对象创建
        try {
            if (classNames.size() == 0) {
                return;
            }
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                //区分controller,区分service
                if (aClass.isAnnotationPresent(MyController.class)) {
                    //controller 的id 此处不做处理,不取value,就拿类的首字母小写作为id,保存到ioc中
                    String simpleName = aClass.getSimpleName();//DemoController
                    String loweFirstSimpleName = lowerFirst(simpleName); //demoController
                    Object o = aClass.newInstance();
                    ioc.put(loweFirstSimpleName, o);

                } else if (aClass.isAnnotationPresent(MyService.class)) {
                    MyService annotation = aClass.getAnnotation(MyService.class);
                    //获取value值
                    String beanName = annotation.value();
                    if (!"".equals(beanName)) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        String simpleName = aClass.getSimpleName();
                        String name = lowerFirst(simpleName);
                        ioc.put(name, aClass.newInstance());
                    }

                    //service 层往往是有接口的,面向接口开发  此时以接口为id,放入ioc便于接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int i = 0; i < interfaces.length; i++) {
                        Class<?> anInterface = interfaces[i];
                        //以接口的全限定类名作为id放入

                        ioc.put(anInterface.getName(), anInterface.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {

        }
    }

    private List<String> classNames = new ArrayList<>();//缓存扫描到类的全限定类名

    //扫描相关的类,扫描注解
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();

        for(File file: files) {
            if(file.isDirectory()) { // 子package
                // 递归
                doScan(scanPackage + "." + file.getName());  // com.lagou.demo.controller
            }else if(file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }

        }


    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
//        String path = req.getRequestURI();
//        Method method = handlerMapping.get(path);
        //反射调用,需要传入对象,传入参数,  此处无法完成,没有对象缓存,没有参数
//        method.invoke()


        //根据url获取到 我们能够处理当前请求的handler
        Handler handler = getHandler(req);

        if (handler==null){
            resp.getWriter().write("404 not found");
            return;
        }
        //参数绑定
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        Object[] paramValues =new Object[parameterTypes.length];
        //前端传入
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {

            String value = StringUtils.join(param.getValue(), ",");

            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }

            Integer index = handler.getParamIndexMapping().get(param.getKey());
            paramValues[index] = value;//前台传递的参数值,放到对应的位置

        }
        Integer reqIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paramValues[reqIndex]=req;
        Integer respIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paramValues[respIndex]=resp;
                //最终调用handler 的method属性

        Object result = null;
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter printWriter = resp.getWriter();
        try {
//
            final String queryString = getQueryString(req.getQueryString(), "name");
            handler.WhiteList(queryString);

        } catch (Exception e) {
            printWriter.print(e);
            return;
        }
        try {
            handler.getMethod().invoke(handler.getController(),paramValues);
        } catch (Exception e) {

        }
    }



    private String getQueryString(String queryString, String key) {
        String value = null;
        if (queryString ==null){
            return null;
        }
        final String[] split = queryString.split("&");
        for (String s : split) {
            final String[] split1 = s.split("=");
            if (key.equals(split1[0])) {
                value = split1[1];
                break;
            }
        }
        return value;
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }

    //首字母小写
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);

    }
}
